/**
 * 主菜单 - 主菜单导航
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.Home.MainMenu.MenuNavForm", {
  extend: "PSI.AFX.Form.EditForm",

  config: {
    mainMenuData: null,

    // 当前登录用户名称
    userName: "",
  },

  /**
   * 初始化组件
   * 
   * @override
   */
  initComponent() {
    const me = this;

    const prodName = PSI.Const.PROD_NAME;

    const year = new Date().getFullYear();
    const c = `Copyright &copy; 2015-${year} PSI Team, All Rights Reserved`;
    const logo = `${PSI.Const.BASE_URL}Public/Images/icons/psi_xl.png`;

    const userName = me.getUserName();

    PCL.apply(me, {
      header: false,
      shadow: false,
      width: 900,
      height: 540,
      layout: "border",
      onEsc: me._onClose,
      closable: true,
      modal: false,
      listeners: {
        show: {
          fn: me._onWndShow,
          scope: me
        },
      },
      items: [{
        region: "center",
        layout: "border",
        border: 0,
        items: [
          {
            region: "north",
            border: 0,
            id: me.buildId(me, "mainPanel"),
            height: 32,
          },
          {
            region: "center",
            border: 0,
            bodyPadding: "0 10 5 0",
            html: `
              <img src="${logo}"
                style="margin-top: 30px;margin-right: 10px;margin-left:20px;width:32px;float:left" />
              <h1 style='color:#003a8c;margin-top:30px;margin-left:20px;padding-left:5px'>
                ${prodName} - 赋能企业信息化升级
              </h1>
              <h2 style="margin-left:20px;margin-top: 60px;color:#003a8c;padding-left: 5px;">
                管理就是界定企业的使命，并激励和组织人力资源去实现这个使命。界定使命是企业家的任务，而激励与组织人力资源是领导力的范畴，二者的结合就是管理。
              </h2>
              <div style="text-align: right;margin-right: 30px;color:#003a8c;">彼得·德鲁克</div>
              <div style='margin-left:20px;margin-top:150px;font-size:14px'>
                <p style='margin-left:10px'>          
                  <span style='color:#196d6d'>当前用户：</span><span style='border-bottom: 2px solid #69c0ff'>${userName}</span>
                </p>
                <p  style='margin-left:10px'>
                  <span style='color:#196d6d'>登录时间：</span><span id='PSI_MainMenu_MenuNavForm_userLoginDT'></span>
                </p>
                <p style='margin-left:10px'>${c}</p>
              </div>
            `
          }
          , {
            region: "west",
            width: 200,
            border: 0,
            layout: "fit",
            bodyPadding: "0 0 5 0",
            items: me.getRecentGrid()
          }
        ]
      }],
      buttons: [{
        text: `退出${prodName}`,
        height: 30,
        handler() {
          me.confirm(`请确认是否退出${prodName} ?`, () => {
            location.replace(me.URL("Home/MainMenu/navigateTo/fid/-9999"));
          }, { x: 180, y: 180 });
        },
      }, "->", {
        text: "关闭",
        width: 120,
        height: 30,
        id: me.buildId(me, "btnOK"),
        handler() {
          me.close();
        },
        scope: me
      }]
    });

    me.callParent(arguments);
  },

  /**
   * 常用功能Grid
   * 
   * @private
   */
  getRecentGrid() {
    const me = this;
    if (me._recentGrid) {
      return me._recentGrid;
    }

    const modelName = me.buildModelName(me, "FId");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["fid", "name"]
    });

    const storeRecentFid = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me._recentGrid = PCL.create("PCL.grid.Panel", {
      header: {
        title: "常用功能",
        height: 28
      },
      border: 1,
      titleAlign: "center",
      cls: "PSI-recent-fid",
      forceFit: true,
      hideHeaders: true,
      columns: [{
        dataIndex: "name",
        menuDisabled: true,
        menuDisabled: true,
        sortable: false,
        width: 16,
        renderer(value, metaData, record) {
          const fid = record.get("fid");
          const getFileName = (fid) => {
            // 码表
            const isCodeTable = fid.substring(0, 2) == "ct";
            if (isCodeTable) {
              return "Public/Images/fid/fid_todo.png";
            }

            // 自定义表单
            const isForm = fid.substring(0, 2) == "fm"
            if (isForm) {
              return "Public/Images/fid/fid_todo.png";
            }

            // TODO 还需要处理LCAP的其他模块

            return `Public/Images/fid/fid${fid}.png`;
          }

          const fileName = getFileName(fid);
          const url = me.URL(fileName);

          return `
          <a href='#' style='text-decoration:none'>
            <img src='${url}' style='vertical-align: middle;margin:0px 5px 0px 5px'></img>
          </a>
          `;
        }
      }, {
        dataIndex: "name",
        menuDisabled: true,
        menuDisabled: true,
        sortable: false,
        renderer(value, metaData, record) {
          return `
          <a href='#' style='text-decoration:none' title='${value}'>
            <span style='vertical-align: middle'>${value}</span>
          </a>
          `;
        }
      }],
      store: storeRecentFid
    });

    const theForm = me;
    me._recentGrid.on("cellclick", (me, td, cellIndex, r, tr, rowIndex, e, eOpts) => {
      theForm.close();

      const fid = r.get("fid");

      const url = `${PSI.Const.BASE_URL}Home/MainMenu/navigateTo/fid/${fid}/t/1`;

      if (fid === "-9999") {
        // TODO 在常用功能里面，应该是没有重新登录这项
        PSI.MsgBox.confirm("请确认是否重新登录", function () {
          location.replace(url);
        });
      } else {
        if (PSI.Const.MOT == "0") {
          // 模块打开方式：原窗口打开
          if (cellIndex == 2) {
            // 新窗口打开
            window.open(url);
            // 清除当前选中项，为了更好的视觉效果
            me.getSelectionModel().deselectAll();
          }
          else {
            location.replace(url);
          }
        } else {
          // 模块打开方式：新窗口打开
          window.open(url);
          // 清除当前选中项，为了更好的视觉效果
          me.getSelectionModel().deselectAll();
        }
      }
    }, me);

    return me._recentGrid;
  },

  /**
   * @private
   */
  _onWndShow() {
    const me = this;

    me.getEl().dom.onmousemove = (e) => {
      me._x = e.clientX;
      me._y = e.clientY;
    }

    me.getEl().dom.onmouseleave = (e) => {
      if (me._x >= me.getWidth() - 50 || me._y >= me.getHeight() - 50) {
        Ext.create("PCL.fx.Anim", {
          target: me,
          from: { opacity: 1 }, // 初始状态为完全不透明
          to: { opacity: 0 }, // 最终状态为完全透明
          duration: 1000, // 动画持续时间毫秒
          listeners: {
            afteranimate: {
              fn() {
                me.close();
              },
              scope: me,
            }
          }
        });

        Ext.menu.Manager.hideAll();
      }
    }

    me.createMainMenu(me.getMainMenuData());

    // 查询常用功能数据
    const store = me.getRecentGrid().getStore();
    store.removeAll();

    me.ajax({
      url: me.URL("Home/MainMenu/recentFid"),
      callback(opt, success, response) {
        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
        }
      },
      scope: me
    });

    // 查询用户登录时间
    me.ajax({
      url: me.URL("Home/User/queryLoginDT"),
      callback(opt, success, response) {
        if (success) {
          const { loginDT, delta } = me.decodeJSON(response.responseText);
          const span = document.getElementById("PSI_MainMenu_MenuNavForm_userLoginDT");
          if (span) {
            span.innerText = `${loginDT} (登录后已持续在线${delta})`;
          }
        }
      },
      scope: me
    });

    PCL.getCmp(me.buildId(me, "btnOK")).focus();
  },

  _onClose() {
    const me = this;
    me.close();
  },

  /**
   * 创建主菜单
   * 
   * @private 
   */
  createMainMenu(root) {
    const me = this;

    const needOpenInNewWindow = (fid) => {
      // 指南、重新登录这些菜单项目，不需要显示在新窗口中打开
      if (fid == "-9995" || fid == "-9999") {
        return false;
      }

      return true;
    };

    const menuItemClick = (item) => {
      me.close();

      const fid = item.fid;

      if (fid == "-9995") {
        window.open(me.URL("Home/Help/index"));
      } else if (fid === "-9999") {
        // 重新登录
        PSI.MsgBox.confirm(`请确认是否重新登录${PSI.Const.PROD_NAME} ?`, function () {
          location.replace(me.URL("Home/MainMenu/navigateTo/fid/-9999"));
        });
      } else {
        const url = me.URL(`Home/MainMenu/navigateTo/fid/${fid}`);
        if (PSI.Const.MOT == "0") {
          if (item.inNewWindow) {
            window.open(url);
          } else {
            location.replace(url);
          }
        } else {
          window.open(url);
        }
      }
    };

    const mainMenu = [];

    const getIconCls = (fid) => {
      const isCodeTable = fid.substring(0, 2) == "ct";
      if (isCodeTable) {
        return "PSI-fid_todo";
      }

      // TODO 还需要处理LCAP其他模块

      return `PSI-fid${fid}`;
    };

    root.forEach((m1) => {
      const menuItem = PCL.create("PCL.menu.Menu", { plain: true });
      m1.children.forEach((m2) => {
        if (m2.children.length === 0) {
          // 只有二级菜单
          if (m2.fid) {
            if (PSI.Const.MOT != "0" || !needOpenInNewWindow(m2.fid)) {
              menuItem.add({
                text: m2.caption,
                fid: m2.fid,
                handler: menuItemClick,
                iconCls: getIconCls(m2.fid)
              });
            } else {
              // 两种打开方式：原窗口和新窗口
              menuItem.add({
                xtype: "buttongroup",
                columns: 2,
                bodyBorder: 0,
                bodyPadding: 0,
                cls: "PSI-mainmenu-btngroup2",
                items: [{
                  text: m2.caption,
                  iconCls: getIconCls(m2.fid),
                  width: 200,
                  textAlign: "left",
                  height: 28,
                  fid: m2.fid,
                  handler: menuItemClick,
                  tooltip: `<span style='color:#9254de'>单击进入</span>【${m2.caption}】`,
                }, {
                  tooltip: `<span style='color:#963838'>新窗口打开</span>【${m2.caption}】`,
                  text: "...",
                  width: 42,
                  height: 28,
                  iconCls: "PSI-open-in-new-window",
                  fid: m2.fid,
                  inNewWindow: true,
                  handler: menuItemClick,
                }]
              });
            }
          }
        } else {
          const menuItem2 = PCL.create("PCL.menu.Menu", { plain: true });

          menuItem.add({
            text: m2.caption,
            menu: menuItem2
          });

          // 三级菜单
          m2.children.forEach((m3) => {
            if (PSI.Const.MOT != "0") {
              // 这时候只有新窗口打开这一种方式
              menuItem2.add({
                text: m3.caption,
                fid: m3.fid,
                handler: menuItemClick,
                iconCls: getIconCls(m3.fid)
              });
            } else {
              // 两种打开方式：原窗口和新窗口
              menuItem2.add({
                xtype: "buttongroup",
                columns: 2,
                bodyBorder: 0,
                bodyPadding: 0,
                cls: "PSI-mainmenu-btngroup2",
                items: [{
                  text: m3.caption,
                  iconCls: getIconCls(m3.fid),
                  width: 200,
                  textAlign: "left",
                  height: 28,
                  fid: m3.fid,
                  handler: menuItemClick,
                  tooltip: `<span style='color:#9254de'>单击进入</span>【${m3.caption}】`,
                }, {
                  tooltip: `<span style='color:#963838'>新窗口打开</span>【${m3.caption}】`,
                  text: "...",
                  width: 42,
                  height: 28,
                  iconCls: "PSI-open-in-new-window",
                  fid: m3.fid,
                  inNewWindow: true,
                  handler: menuItemClick,
                }]
              });
            }
          });
        }
      });

      if (m1.children.length > 0) {
        mainMenu.push({
          text: m1.caption,
          menu: menuItem
        });
      }
    });

    const mainToolbar = PCL.create("PCL.toolbar.Toolbar", {
      border: 1,
      dock: "top",
    });
    mainToolbar.add({ xtype: 'tbspacer', width: 10 });
    mainToolbar.add(mainMenu);

    const theCmp = PCL.getCmp(me.buildId(me, "mainPanel"));

    theCmp.addDocked(mainToolbar, "top")
  },
});
